package com.rt.web.controller.system;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;

import com.rt.system.mapper.SysRoleMapper;
import com.rt.system.service.ISysRoleService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.rt.common.annotation.Log;
import com.rt.common.core.controller.BaseController;
import com.rt.common.core.domain.AjaxResult;
import com.rt.common.enums.BusinessType;
import com.rt.system.domain.RtQuestionsInfo;
import com.rt.system.service.IRtQuestionsInfoService;
import com.rt.common.utils.poi.ExcelUtil;
import com.rt.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 试题Controller
 * 
 * @author Yg
 * @date 2022-04-13
 */
@RestController
@RequestMapping("/system/questions")
public class RtQuestionsInfoController extends BaseController
{
    @Autowired
    private IRtQuestionsInfoService rtQuestionsInfoService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 查询试题列表
     */
    @PreAuthorize("@ss.hasPermi('system:questions:list')")
    @GetMapping("/list")
    public TableDataInfo list(RtQuestionsInfo rtQuestionsInfo)
    {
        for (Integer integer : roleService.selectRoleListByUserId(getUserId())) {
            if (integer!=99 && integer!=1 && integer!=88){
                rtQuestionsInfo.setUserId(getUserId());
                rtQuestionsInfo.setVerityStatus(0);
            }
            if (integer==88){
                rtQuestionsInfo.setExpertName(String.valueOf(getUserId()));
                rtQuestionsInfo.setVerityStatus(0);
            }
        }
        startPage();
        List<RtQuestionsInfo> list = rtQuestionsInfoService.selectRtQuestionsInfoList(rtQuestionsInfo);
        return getDataTable(list);
    }

    /**
     * 查询试题统计列表
     */
    @PreAuthorize("@ss.hasPermi('system:questions:listCount')")
    @GetMapping("/listCount")
    public TableDataInfo listCount(RtQuestionsInfo rtQuestionsInfo)
    {
        startPage();
        List<RtQuestionsInfo> list = rtQuestionsInfoService.selectRtQuestionsInfoCountList(rtQuestionsInfo);
        return getDataTable(list);
    }

    /**
     * 导出试题列表
     */
    @PreAuthorize("@ss.hasPermi('system:questions:export')")
    @Log(title = "试题", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(RtQuestionsInfo rtQuestionsInfo)
    {
        List<RtQuestionsInfo> list = rtQuestionsInfoService.selectRtQuestionsInfoList(rtQuestionsInfo);
        ExcelUtil<RtQuestionsInfo> util = new ExcelUtil<RtQuestionsInfo>(RtQuestionsInfo.class);
        return util.exportExcel(list, "试题数据");
    }

    /**
     * 获取试题详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:questions:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(rtQuestionsInfoService.selectRtQuestionsInfoById(id));
    }

    /**
     * 新增试题
     */
    @PreAuthorize("@ss.hasPermi('system:questions:add')")
    @Log(title = "试题", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RtQuestionsInfo rtQuestionsInfo){
        rtQuestionsInfo.setCreateOperator(getUsername());
        rtQuestionsInfo.setUserId(getUserId());
        return toAjax(rtQuestionsInfoService.insertRtQuestionsInfo(rtQuestionsInfo));
    }

    /**
     * 修改试题
     */
    @PreAuthorize("@ss.hasPermi('system:questions:edit')")
    @Log(title = "试题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RtQuestionsInfo rtQuestionsInfo)
    {
        rtQuestionsInfo.setUpdateOperator(getUsername());
        return toAjax(rtQuestionsInfoService.updateRtQuestionsInfo(rtQuestionsInfo));
    }

    /**
     * 修改试题状态
     */
    @PutMapping("/editStatus")
    public AjaxResult editStatus(@RequestBody RtQuestionsInfo rtQuestionsInfo)
    {
        rtQuestionsInfo.setUpdateOperator(getUsername());
        return toAjax(rtQuestionsInfoService.updateRtQuestionsInfoStatus(rtQuestionsInfo));
    }

    /**
     * 审核
     */
    @PreAuthorize("@ss.hasPermi('system:questions:verity')")
    @PutMapping("/editVerity")
    public AjaxResult editVerity(@RequestBody RtQuestionsInfo rtQuestionsInfo)
    {
        rtQuestionsInfo.setExamineName(getUsername());
        rtQuestionsInfo.setUpdateOperator(getUsername());
        return toAjax(rtQuestionsInfoService.updateRtQuestionsInfoVerityStatus(rtQuestionsInfo));
    }

    /**
     * 调整试题难易度
     */
    @PreAuthorize("@ss.hasPermi('system:questions:edit')")
    @Log(title = "试题", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult editDifficulty()
    {
        return toAjax(rtQuestionsInfoService.editDifficulty(getUsername()));
    }

    /**
     * 删除试题
     */
    @PreAuthorize("@ss.hasPermi('system:questions:remove')")
    @Log(title = "试题", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String id)
    {
        String operName=getUsername();
        return toAjax(rtQuestionsInfoService.deleteRtQuestionsInfoById(id,operName));
    }

//    @GetMapping("/importTemplate")
//    public void downloadFile(HttpServletResponse response) throws IOException {
//        try {
//            Resource resource = new ClassPathResource("excel/试题格式.doc");
//            File file = resource.getFile();
//            String filename = resource.getFilename();
//            InputStream inputStream = new FileInputStream(file);
//            //强制下载不打开
//            response.setContentType("application/force-download");
//            OutputStream out = response.getOutputStream();
//            //使用URLEncoder来防止文件名乱码或者读取错误
//            response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename, "UTF-8"));
//            int b = 0;
//            byte[] buffer = new byte[1000000];
//            while (b != -1) {
//                b = inputStream.read(buffer);
//                if(b!=-1) out.write(buffer, 0, b);
//            }
//            inputStream.close();
//            out.close();
//            out.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 下载导题模板
     * @param response
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult downloadFile(HttpServletResponse response) {
        try {
            String templateName = "报名表-模板";
            Resource resource = new ClassPathResource("excel/" + templateName + ".xls");
            InputStream inputStream = resource.getInputStream();

            // 设置响应头
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + templateName + ".xls\"");

            // 将文件内容写入到响应输出流中
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }

            inputStream.close();
            response.flushBuffer();

            return AjaxResult.success("导出成功");
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，例如返回错误响应等
            return AjaxResult.error("导出模版错误请联系工作人员");
        }
    }



    @Log(title = "试题word导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        String message =rtQuestionsInfoService.importData(file,getUserId(),getUsername());
        return AjaxResult.success(message);
    }
}
